package com.baitiaojun.bulletscreen.timer;

import com.alibaba.fastjson.JSONObject;
import com.baitiaojun.api.domain.video.BulletScreen;
import com.baitiaojun.api.domain.video.BulletScreenMqDuplicate;
import com.baitiaojun.api.exception.ConditionException;
import com.baitiaojun.bulletscreen.service.BulletScreenMqDuplicateService;
import com.baitiaojun.bulletscreen.service.BulletScreenService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @类名 BulletScreenMqDuplicateTimer
 * @描述 TODO
 * @作者 白条君
 * @创建日期 2023/1/3 15:12
 * @版本 1.0
 */
@Slf4j
@Component
public class BulletScreenMqDuplicateTimer {

    @Autowired
    private BulletScreenMqDuplicateService duplicateService;

    @Autowired
    private BulletScreenService bulletScreenService;

    @Transactional
    @Scheduled(initialDelay = 3000, fixedRate = 10000)
    public void saveBulletScreenMqDuplicate() throws ConditionException {
        log.info("定时器任务重发...");
        List<BulletScreenMqDuplicate> bulletScreenMqDuplicates = duplicateService.getBulletScreenMqDuplicate("2");
        if (ObjectUtils.isNotEmpty(bulletScreenMqDuplicates)) {
            List<BulletScreen> bulletScreens = bulletScreenMqDuplicates.stream()
                    .map(bulletScreenMqDuplicate ->
                            JSONObject.parseObject(bulletScreenMqDuplicate.getContent(), BulletScreen.class))
                    .collect(Collectors.toList());
            bulletScreenService.batchSaveBulletScreenMqDuplicate(bulletScreens);
            bulletScreenMqDuplicates = bulletScreenMqDuplicates.stream()
                    .peek(bulletScreenMqDuplicate -> bulletScreenMqDuplicate.setUpdatetime(new Date()))
                    .collect(Collectors.toList());
            duplicateService.batchUpdateBulletScreenMqDuplicate(bulletScreenMqDuplicates);
        }
    }
}
